package com.changgou.oauth.controller;

import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import com.changgou.oauth.util.CookieTools;
import com.changgou.util.Result;
import com.changgou.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*****
 * @Author: 黑马训练营
 * @Description: com.changgou.oauth.controller
 ****/
@RestController
@RequestMapping(value = "/user")
@CrossOrigin
public class AuthController {

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String secret;

    @Autowired
    private AuthService authService;

    /****
     * 登录方法
     */
    @PostMapping(value = "/login")
    public Result login(String username, String password, HttpServletRequest request, HttpServletResponse response){
        //登录
        AuthToken authToken = authService.login("password",username,password,clientId,secret);

        //获取用户令牌，将令牌存入到Cookie
        CookieTools.setCookie(request, response, "Authorization",authToken.getAccessToken(), true);
        CookieTools.setCookie(request, response, "cuname",username, true);
        return new Result(true, StatusCode.OK,"登录成功！",authToken);
    }

}
